package com.renwei.yunlong.activity.work;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.CardView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ZoomControls;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.trace.model.SortType;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.renwei.yunlong.R;
import com.renwei.yunlong.base.BaseActivity;
import com.renwei.yunlong.bean.WorkTrackBean;
import com.renwei.yunlong.http.Api;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.CommonUtils;
import com.renwei.yunlong.utils.DateTimeUtils;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.PermissionUtil;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;
import com.zyf.fwms.commonlibrary.utils.GlideCircleTransform;
import com.zyf.fwms.commonlibrary.utils.StatusBarUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

public class WorkTrackMapActivity extends BaseActivity implements RationaleListener, PermissionListener, HttpTaskListener {

    @Bind(R.id.bmapView)
    MapView mMapView;
    @Bind(R.id.iv_back)
    ImageView ivBack;
    @Bind(R.id.iv_head)
    ImageView ivHead;
    @Bind(R.id.tv_name)
    TextView tvName;
    @Bind(R.id.tv_group)
    TextView tvGroup;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.tv_work_order)
    TextView tvWorkOrder;
    @Bind(R.id.tv_company)
    TextView tvCompany;
    @Bind(R.id.tv_chufa_time)
    TextView tvChufaTime;
    @Bind(R.id.tv_time)
    TextView tvTime;
    @Bind(R.id.tv_daoda_time)
    TextView tvDaodaTime;
    @Bind(R.id.cardview)
    CardView cardview;
    @Bind(R.id.iv_loca)
    ImageView ivLoca;
    private BaiduMap mBaiduMap;
    private BitmapDescriptor iconStart;
    private BitmapDescriptor iconEnd;
    private String requestId;

    private boolean isReset = false;
    private String outsourceFlag;
    private String from;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_work_track_map);
        ButterKnife.bind(this);
        PermissionUtil.checkSinglePermission(this, this, this, Permission.LOCATION);
        StatusBarUtil.setColor(this, CommonUtils.getColor(this, R.color.black_top), 0);
        requestId = getIntent().getStringExtra("requestId");
        outsourceFlag = getIntent().getStringExtra("outsourceFlag");
        from = getIntent().getStringExtra("from");

        // 隐藏logo
        View child = mMapView.getChildAt(1);
        if (child != null && (child instanceof ImageView || child instanceof ZoomControls)){
            child.setVisibility(View.INVISIBLE);
        }
        // 隐藏 比例尺和加减号
        mMapView.showScaleControl(false);
        mMapView.showZoomControls(false);
        mBaiduMap = mMapView.getMap();

        ivLoca.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isReset) {
                    isReset = false;
                    cardview.setVisibility(View.VISIBLE);
                    ivLoca.setImageResource(R.mipmap.icon_map_clean);
                } else {
                    isReset = true;
                    cardview.setVisibility(View.GONE);
                    ivLoca.setImageResource(R.mipmap.icon_map_reset);
                }
            }
        });
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        initData();
    }

    private void initData() {
        final View view = LayoutInflater.from(mContext).inflate(R.layout.view_map_icon, null);
        RelativeLayout rlMap = view.findViewById(R.id.rl_map);

        rlMap.setBackgroundResource(R.mipmap.icon_map_start);
        iconStart = BitmapDescriptorFactory.fromView(view);
        if ("出发".equals(from)){
            rlMap.setBackgroundResource(R.mipmap.icon_map_default_person);
        }else{
            rlMap.setBackgroundResource(R.mipmap.icon_map_end);
        }
        iconEnd = BitmapDescriptorFactory.fromView(view);

        HashMap<String, String> map = new HashMap<>();
        map.put("requestId", requestId);
        ServiceRequestManager.getManager().getWorkLatLng(this, outsourceFlag, JsonMapUtil.mapToJson(map), this);
    }

    @Override
    protected void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        mMapView.onResume();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        // 退出时销毁定位
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        mMapView.onDestroy();
        mMapView = null;
        super.onDestroy();
    }


    @Override
    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
        AndPermission.rationaleDialog(this, rationale).show();
    }

    @Override
    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
        switch (requestCode) {
            case PermissionUtil.LOCATION:
                initData();
                break;
                default:
                break;

        }
    }

    @Override
    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
        // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
        if (AndPermission.hasAlwaysDeniedPermission(this, deniedPermissions)) {
            // 第一种：用默认的提示语。
            AndPermission.defaultSettingDialog(this, PermissionUtil.SETTING_CODE).show();
        }
    }

    @Override
    public void onSuccess(int requestId, String result) {
        WorkTrackBean workTrackBean = new Gson().fromJson(result, WorkTrackBean.class);
        if (workTrackBean.getMessage().getCode() == 200) {
            setMapTrack(workTrackBean);
        }
    }

    private void setMapTrack(WorkTrackBean workTrackBean) {
        WorkTrackBean.RowsBean rows = workTrackBean.getRows();
        String url = "1".equals(companyType) ? Api.$().OWNER_FILE_URL + ownerBean.getRows().getAvatar()
                : Api.$().SERVICE_FILE_URL + serviceLoginBean.getRows().getAvatar();
        Glide.with(mContext).load(url).error(R.mipmap.icon_header_default).
                transform(new GlideCircleTransform(this)).into(ivHead);
        tvName.setText(rows.getName());
        if (TextUtils.isEmpty(rows.getGroupUserNames())) {
            tvGroup.setText(rows.getDepartmentName());
        } else {
            tvGroup.setText(rows.getDepartmentName() + "/" + rows.getGroupUserNames());
        }

        tvWorkOrder.setText(rows.getWorkOrder());
        tvCompany.setText("客户：" + rows.getCustomer());

        if (!TextUtils.isEmpty(rows.getOutTime())) {
            tvChufaTime.setText(DateTimeUtils.getMMddHHmm(rows.getOutTime().replace("T", " ")));
        }
        if (!TextUtils.isEmpty(rows.getEnterTime())) {
            tvDaodaTime.setText(DateTimeUtils.getMMddHHmm(rows.getEnterTime().replace("T", " ")));
        }
        tvTime.setText(rows.getDistanceTime());

        List<LatLng> points = new ArrayList<>();
        List<WorkTrackBean.RowsBean.AppPositionLocationListBean> locationList = rows.getAppPositionLocationList();
        if (locationList != null) {
            if (locationList.size() == 1) {
                points.add(new LatLng(Double.parseDouble(locationList.get(0).getLatitude()), Double.parseDouble(locationList.get(0).getLongitude())));
                points.add(new LatLng(Double.parseDouble(locationList.get(0).getLatitude()), Double.parseDouble(locationList.get(0).getLongitude())));
            } else {
                for (WorkTrackBean.RowsBean.AppPositionLocationListBean bean : locationList) {
                    points.add(new LatLng(Double.parseDouble(bean.getLatitude()), Double.parseDouble(bean.getLongitude())));
                }
            }
            drawHistoryTrack(points, SortType.asc);
        } else {
            showCenterInfoMsg("当前未查询到工单轨迹");
        }
    }

    /**
     * 绘制历史轨迹
     */
    public void drawHistoryTrack(List<LatLng> points, SortType sortType) {
        // 绘制新覆盖物前，清空之前的覆盖物
        mBaiduMap.clear();
        if (points == null || points.size() == 0) {
            return;
        }

        LatLng startPoint;
        LatLng endPoint;
        if (sortType == SortType.asc) {
            startPoint = points.get(0);
            endPoint = points.get(points.size() - 1);
        } else {
            startPoint = points.get(points.size() - 1);
            endPoint = points.get(0);
        }

        // 添加起点图标
        OverlayOptions startOptions = new MarkerOptions()
                .position(startPoint).icon(iconStart)
                .zIndex(9).draggable(true);

        // 添加终点图标
        OverlayOptions endOptions;
        if ("出发".equals(from)){
            endOptions = new MarkerOptions().position(endPoint)
                    .icon(iconEnd).zIndex(9).draggable(true);
        }else{
            endOptions = new MarkerOptions().position(endPoint)
                    .icon(iconEnd).zIndex(9).draggable(true);
        }


        // 添加路线（轨迹）
        OverlayOptions polylineOptions = new PolylineOptions().width(10)
                .color(Color.BLUE).points(points);

        mBaiduMap.addOverlay(startOptions);
        mBaiduMap.addOverlay(endOptions);
        mBaiduMap.addOverlay(polylineOptions);
        animateMapStatus(startPoint, 16);
    }

    public void animateMapStatus(LatLng point, float zoom) {
        MapStatus.Builder builder = new MapStatus.Builder();
        MapStatus mapStatus = builder.target(point).zoom(zoom).build();
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(mapStatus));
    }

    @Override
    public void onException(int requestId, String code) {
        showTopWrongMsg(getResources().getString(R.string.net_work_error));
    }

    public static void OpenActivity(Context context, String requestId, String outsourceFlag,String from) {
        Intent intent = new Intent(context, WorkTrackMapActivity.class);
        intent.putExtra("requestId", requestId);
        intent.putExtra("outsourceFlag", outsourceFlag);
        intent.putExtra("from", from);
        context.startActivity(intent);
    }
}
